<template>
  <div class="stock-container">


    <!-- Loading State -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner">
        <div class="spinner"></div>
      </div>
      <div class="loading-text">加载中...</div>
      <!-- Skeleton Loading -->
      <div class="skeleton-list">
        <div v-for="i in 6" :key="i" class="skeleton-item">
          <div class="skeleton-line skeleton-title"></div>
          <div class="skeleton-line skeleton-subtitle"></div>
        </div>
      </div>
    </div>

    <!-- Stock List -->
    <div v-else-if="!loading && displayedStocks.length > 0" class="stock-list">
      <div
          v-for="(stock, index) in displayedStocks"
          :key="`${stock.stockSymbol}-${stock.stockNumber}-${index}`"
          class="stock-item"
          @click="navigateToStock(stock)"
      >
        <div class="stock-info">
          <div class="stock-symbol">{{ stock.stockSymbol }}</div>
          <div class="stock-number">#{{ stock.stockNumber }}</div>
        </div>
        <div class="arrow-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="9,18 15,12 9,6"></polyline>
          </svg>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else-if="!loading && displayedStocks.length === 0" class="empty-state">
      <div class="empty-icon">📊</div>
      <div class="empty-text">暂无股票数据</div>
      <button @click="fetchStocks" class="retry-button">重新加载</button>
    </div>

    <!-- Pagination -->
    <div v-if="!loading && totalPages > 1" class="pagination-container">
      <div class="pagination-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页 ({{ totalItems }} 条记录)
      </div>
      <div class="pagination-controls">
        <button
            @click="goToPage(currentPage - 1)"
            :disabled="currentPage <= 1"
            class="pagination-button"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="15,18 9,12 15,6"></polyline>
          </svg>
        </button>

        <div class="page-numbers">
          <button
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="['page-number', { active: page === currentPage }]"
              :disabled="page === '...'"
          >
            {{ page }}
          </button>
        </div>

        <button
            @click="goToPage(currentPage + 1)"
            :disabled="currentPage >= totalPages"
            class="pagination-button"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="9,18 15,12 9,6"></polyline>
          </svg>
        </button>
      </div>
    </div>

    <!-- Back to Top Button -->
    <transition name="fade">
      <button
          v-if="showBackToTop"
          @click="scrollToTop"
          class="back-to-top"
          aria-label="回到顶部"
      >
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="18,15 12,9 6,15"></polyline>
        </svg>
      </button>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import {getStockNumAndSymbols} from "@/api/stock/stocks";
// 响应式数据
const loading = ref(false)
const allStocks = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const showBackToTop = ref(false)

// API调用函数 - 适配您的后端数据格式
const fetchStocksFromAPI = async (page = 1, size = 10) => {
  try {
    // 调用您的后端API函数
    const { code, data } = await getStockNumAndSymbols()

    if (code === 200) {
      // 客户端分页处理
      const startIndex = (page - 1) * size
      const endIndex = startIndex + size
      const paginatedData = data.slice(startIndex, endIndex)

      return {
        data: paginatedData,
        total: data.length,
        page: page,
        pageSize: size,
        totalPages: Math.ceil(data.length / size)
      }
    } else {
      throw new Error(`API返回错误，状态码: ${code}`)
    }

  } catch (error) {
    console.error('API调用失败:', error)
    throw error
  }
}

// 计算属性
const displayedStocks = computed(() => allStocks.value)

const totalItems = ref(0)
const totalPages = ref(0)

const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value

  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }

  return pages
})

// 方法
const fetchStocks = async (page = 1) => {
  try {
    loading.value = true
    const result = await fetchStocksFromAPI(page, pageSize.value)

    allStocks.value = result.data
    totalItems.value = result.total
    totalPages.value = result.totalPages
    currentPage.value = result.page

  } catch (error) {
    console.error('获取股票数据失败:', error)
    // 可以在这里添加错误提示，例如使用 toast 或者 message 组件
    allStocks.value = []
    totalItems.value = 0
    totalPages.value = 0
  } finally {
    loading.value = false
  }
}

const goToPage = async (page) => {
  if (page < 1 || page > totalPages.value || page === currentPage.value || page === '...') return

  await fetchStocks(page)
  await nextTick()
  scrollToTop()
}

import router from "@/router";

const navigateToStock = (stock) => {

   router.push({
    path: '/center/stockInformation',
    query: {
      stockSymbol: stock.stockSymbol,
      stockNumber: stock.stockNumber
    }
  })

}

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

const handleScroll = () => {
  showBackToTop.value = window.scrollY > 300
}

// 生命周期
onMounted(async () => {
  await fetchStocks()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

// 监听器
watch(currentPage, () => {
  scrollToTop()
})
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.stock-container {
  min-height: 100vh;
  background: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding: 2rem 0;
}

/* Stock List */
.stock-list {
  padding: 0 1.5rem 2rem;
}
/* Loading Styles */
.loading-container {
  text-align: center;
  padding: 2rem;
}

.loading-spinner {
  margin: 0 auto 1rem;
  width: 50px;
  height: 50px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f1f3f4;
  border-top: 4px solid #000000;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 1.1rem;
  color: #666666;
  margin-bottom: 2rem;
}

.skeleton-list {
  padding: 0 1.5rem;
}

.skeleton-item {
  background: #fff;
  border-radius: 16px;
  margin-bottom: 1rem;
  padding: 1.5rem;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
  border: 1px solid #e5e5e5;
}

.skeleton-line {
  height: 20px;
  background: linear-gradient(90deg, #f8f9fa 25%, #e9ecef 50%, #f8f9fa 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  border-radius: 4px;
}

.skeleton-title {
  width: 30%;
  margin-bottom: 0.5rem;
}

.skeleton-subtitle {
  width: 20%;
  height: 16px;
}

@keyframes skeleton-loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* Stock List */
.stock-list {
  padding: 0 1.5rem 2rem;
}

.stock-item {
  background: #fff;
  border-radius: 16px;
  margin-bottom: 1rem;
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
  border: 1px solid #e5e5e5;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.stock-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: #000000;
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.stock-item:hover::before,
.stock-item:active::before {
  transform: scaleY(1);
}

.stock-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(0,0,0,0.1);
  border-color: #cccccc;
}

.stock-item:active {
  transform: translateY(0);
  transition: transform 0.1s ease;
}

.stock-info {
  flex: 1;
}

.stock-symbol {
  font-size: 1.3rem;
  font-weight: 700;
  color: #000000;
  margin-bottom: 0.25rem;
  letter-spacing: 0.5px;
}

.stock-number {
  font-size: 0.9rem;
  color: #666666;
  font-weight: 500;
}

.arrow-icon {
  color: #999999;
  transition: all 0.3s ease;
}

.stock-item:hover .arrow-icon {
  color: #000000;
  transform: translateX(3px);
}

/* Empty State */
.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  color: #666666;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.empty-text {
  font-size: 1.1rem;
  margin-bottom: 2rem;
  color: #666666;
}

.retry-button {
  background: #000000;
  color: #fff;
  border: none;
  padding: 0.8rem 2rem;
  border-radius: 25px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.retry-button:hover {
  background: #333333;
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}

/* Pagination */
.pagination-container {
  padding: 2rem 1.5rem 3rem;
  text-align: center;
}

.pagination-info {
  color: #666666;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.pagination-button {
  background: #fff;
  border: 2px solid #e5e5e5;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666666;
}

.pagination-button:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.pagination-button:not(:disabled):hover {
  border-color: #000000;
  background: #000000;
  color: #fff;
}

.page-numbers {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.page-number {
  background: #fff;
  border: 2px solid #e5e5e5;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  color: #666666;
}

.page-number:disabled {
  cursor: default;
  background: transparent;
  border: none;
  color: #999999;
}

.page-number.active {
  background: #000000;
  border-color: #000000;
  color: #fff;
}

.page-number:not(.active):not(:disabled):hover {
  border-color: #000000;
  color: #000000;
}

/* Back to Top Button */
.back-to-top {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 50px;
  height: 50px;
  background: #000000;
  color: #fff;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  transition: all 0.3s ease;
  z-index: 1000;
}

.back-to-top:hover {
  background: #333333;
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(0,0,0,0.4);
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .stock-list, .skeleton-list {
    padding: 0 1rem 2rem;
  }

  .stock-item, .skeleton-item {
    padding: 1.2rem;
    margin-bottom: 0.8rem;
  }

  .stock-symbol {
    font-size: 1.2rem;
  }

  .stock-number {
    font-size: 0.85rem;
  }

  .pagination-container {
    padding: 2rem 1rem 3rem;
  }

  .pagination-controls {
    gap: 0.25rem;
  }

  .pagination-button,
  .page-number {
    width: 35px;
    height: 35px;
    font-size: 0.9rem;
  }

  .back-to-top {
    bottom: 1.5rem;
    right: 1.5rem;
    width: 45px;
    height: 45px;
  }
}
/* 触摸优化 */
@media (hover: none) {
  .stock-item:hover {
    transform: none;
  }

  .stock-item:active {
    transform: scale(0.98);
    transition: transform 0.1s ease;
  }

  .pagination-button:active,
  .page-number:active {
    transform: scale(0.95);
  }
}
</style>